package com.jdkreader.concurrency.concurrent.semaphore;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 信号量运行主类
 */
public class SemaphoreDemo {
    //对象池大小
    private static final int SIZE=25;

    public static void main(String[] args) throws Exception{
        final Pool<Fat> pool=new Pool<Fat>(Fat.class,SIZE);

        ExecutorService exec= Executors.newCachedThreadPool();
        for(int i=0;i<SIZE;i++){
            exec.execute(new CheckOutTask<Fat>(pool));
        }
        System.out.println("All checkOutTask created");
        List<Fat> list=new ArrayList<Fat>();
        for(int i=0;i<SIZE;i++){
            Fat fat=pool.checkOut();
            System.out.println(i+" main() thread checked out ");
            fat.operation();
            list.add(fat);
        }

        Future<?> blocked=exec.submit(() ->{
            try{
                //对象池对象已经全部检出，再次进行检出操作，信号量会将操作进行阻塞
                pool.checkOut();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        });
        TimeUnit.SECONDS.sleep(2);
        blocked.cancel(true);//取消被阻塞的操作
        for(Fat f:list){
            pool.checkIn(f);
        }
        exec.shutdownNow();
    }
}
